'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') //生产环境取消打印
const CompressionWebpackPlugin = require('compression-webpack-plugin') //gzip压缩
const productionGzipExtensions = ['js', 'css']

function resolve(dir) {
  return path.join(__dirname, dir)
}

// 网站标题
const name = defaultSettings.title || 'vue Admin Template' // page title
// 开发环境下运行端口号
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

let externals = {}
let cdn = { css: [], js: [] }
const idProd = process.env.NODE_ENV === 'production'
if(idProd){
  externals = {}
  // 注意cdn资源的版本尽量和package.json里面的版本一致
  cdn = {
     // 放置css文件目录
    css: [],
    // 放置js文件目录
    js: [] 
  }
}
// 详细配置参见 https://cli.vuejs.org/config/
module.exports = {
  css: {
    extract: true,
    sourceMap: false
  },
  // 打包后的资源路径关系
  publicPath:idProd ? './' : '/',
  // 打包输出目录
  outputDir: 'dist',
  // 静态文件目录
  assetsDir: 'static',
  // 判断是否保存就校验
  // lintOnSave: process.env.NODE_ENV === 'development',
  lintOnSave: false,
  // 关闭打包时候的map文件
  productionSourceMap: false, // 默认值为true
  // 服务器相关配置
  devServer: {
    port: port, // 端口号
    open: true, // 是否自动打开浏览器
    overlay: {
      warnings: false,
      errors: true
    },
    // 代理跨域的配置 【仅限于在开发环境下有效果】
    proxy: {
      '/temp': {
        target: 'http://39.185.228.30:15108/release/',
        secure: false, // 如果是https接口，需要配置这个参数
        changeOrigin: true,
        pathRewrite: { "^/temp": "" },
      }
     },
  },
  // configureWebpack: {
  //   // 配置网站名称
  //   name: name,
  //   // 一些解析配置
  //   resolve: {
  //     // 配置别名
  //     alias: {
  //       '@': resolve('src')
  //     }
  //   },
  //   // webpack打包运行排除项； 写在这里的内容，webpack不会打包这些依赖
  //   externals:externals,
  // },
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {
      config.name = '认识康复'
      config.plugins.push(
        // 1、取消打印
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              drop_debugger: true, //生产环境自动删除debugger
              drop_console: true //生产环境自动删除console
            },
            warnings: false
          },
          sourceMap: false, //关掉sourcemap 会生成对于调试的完整的.map文件，但同时也会减慢打包速度
          parallel: true //使用多进程并行运行来提高构建速度。默认并发运行数：os.cpus().length - 1。
        }),
        new CompressionWebpackPlugin({
          filename: '[path][base].gz',
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240,
          minRatio: 0.8
        }),
      )
    } else {
      config.name = '认识康复'
    }
  },
  // webpack的配置
  chainWebpack(config) {
    // 将CDN资源文件，注入到 index.html 模板里面
    config.plugin('html').tap(args => {
      args[0].cdn = cdn
      return args
    })
    // 提高首屏加载速度
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])
    // 多页面应用情况下提高首屏加载速度
    config.plugins.delete('prefetch')
    // 设置 svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
        }
      )
  },
  // i18n
  pluginOptions: {
    i18n: {
      locale: 'zh-chs',
      fallbackLocale: 'ja',
      localeDir: 'locales',
      enableInSFC: true
    }
  }
}
